package com.chixing.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.chixing.config.AlipayConfig;
import com.chixing.pojo.Flow;


import com.chixing.pojo.Myorder;
import com.chixing.service.FlowService;
import com.chixing.service.OrderDetailService;
import com.chixing.service.OrderService;
import com.chixing.service.ProductService;
import com.chixing.util.ServerResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 支付流程
 */
@Controller
public class PayController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductService productService;
    @Autowired
    private FlowService flowService;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 调用支付宝接口
     * @return 返回支付宝支付后的数据
     */
    @PostMapping("alipayy")
    @ResponseBody
    public String alipay(String orderNum,String orderId,Integer productNum){
        System.out.println("订单编号"+orderNum);
        System.out.println("订单id"+orderId);
        System.out.println("商品总数"+productNum);

      Myorder myorder = orderService.getById(orderId);



      //获得初始化的AlipayClient
         AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
                                                             AlipayConfig.merchant_private_key,"json",AlipayConfig.charset,
                                                             AlipayConfig.alipay_public_key,AlipayConfig.sign_type);

         //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        // 支付宝支付完成后，走哪个url : 同步、异步
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = orderId;   //订单id
        Integer total_amount = productNum;   // 订单总金额
        String subject = "猫粮";   //  商品名称
        String body ="用户购买的商品"+"猫粮" + ",数量是:" +productNum;  //  备注
        String timeout_express = "1c";  //  1天内支付

        System.out.println("out_trade_no:"+out_trade_no);
        System.out.println("total_amount:"+total_amount);
        System.out.println("subject:"+subject);
        System.out.println("body:"+body);

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"timeout_express\":\""+ timeout_express +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //发送请求
        //获得支付宝返回数据
        String result =null;
        try {
            result =alipayClient.pageExecute(alipayRequest).getBody();  // 执行支付  --- 支付宝 执行支付，有支付页面
            System.out.println("支付成后，支付宝返回的数据是："+ result);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return result;

    }

    // 支付完成后，我们要如何处理 结果 数据？
    // 调用支付 是同步请求， 该方法就是 同步处理的
    @GetMapping("/alipayReturnNotice")
    public ModelAndView alipayReturnNotice(HttpServletRequest request, HttpServletRequest response, HttpSession session) throws Exception {


        System.out.println("支付成功后，支付宝返回的所有的数据："+ request);
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            System.out.println("return notice name:"+name);
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        System.out.println("params:"+params);
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
        System.out.println("return notice signVerified:"+signVerified);
        ModelAndView mav = new ModelAndView();
        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            System.out.println("return out_trade_no:"+out_trade_no);
            System.out.println("return trade_no:"+trade_no);
            System.out.println("return total_amount:"+total_amount);
            //	System.out.println("return productName:"+ product.getName());


             //1. 新增支付流水 ,修改订单状态，改为 支付成功，已付款;
            Flow flow =  new Flow();
            flow.setId(trade_no);  //???
            flow.setFlowNum(trade_no);  //   ???
            flow.setOrderNum(out_trade_no);  //  ???

            flow.setPaidAmount(total_amount);  //付款金额
            flow.setCreateTime(new Date());
            flow.setProductId("1001");
            flowService.save(flow,out_trade_no);


            mav.setViewName("flow/detail");  // 流水详情中
            mav.addObject("out_trade_no", out_trade_no);
            mav.addObject("trade_no", trade_no);
            mav.addObject("total_amount", total_amount);
            mav.addObject("productName","商品");
            mav.addObject("pay_time", flow.getCreateTime());



        }else {
            System.out.println("支付出错了，验证签名失败");
        }

        return mav;
    }

    // 调用支付 是异步请求， 该方法就是 异步处理的
    @GetMapping("/alipayNotifyNotice")
    public String notifyNotice(){
        return null;
    }


}
